﻿using DevExpress.XtraEditors;
using DevExpress.XtraTab;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace twistmachinev2
{
    public partial class FrmMain3D : XtraForm
    {
        private static readonly Dictionary<string, Assembly> _assemblyCache = new Dictionary<string, Assembly>();
        private static readonly Dictionary<string, Type> _typeCache = new Dictionary<string, Type>();
        int userRights = 0;
        public FrmMain3D()
        {
            InitializeComponent();
            this.FormBorderEffect = DevExpress.XtraEditors.FormBorderEffect.Shadow;
            //userRights = (int)BaseData.SavedPuser.permissionvalue;
            this.Text = BaseData.GetSystemName();
        }

        private void FrmMain3D_Load(object sender, EventArgs e)
        {
            int permission = (int)BaseData.CurrentUserPermission;
            //遍历全部的BarLargeItem，获取其Tag值
            foreach (DevExpress.XtraBars.BarLargeButtonItem item in barManager1.Items.OfType<DevExpress.XtraBars.BarLargeButtonItem>())
            {
                //如果Tag值为null，则跳过
                if (item.Tag == null)
                    continue;
                //如果Tag值为"Admin"，则判断权限是否大于等于60
                if (int.Parse(item.Tag.ToString()) <= permission)
                {
                    item.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                }
                else
                {
                    item.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                }
            }

        }

        private void barLargeButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmSystemSettings");
        }


        private void btnTest_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmZHLineTest");
        }

        private void btnUser_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmUserManagement");
        }
        private void btnCheckProject_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmZHTestGroup");
        }

        private void btnHistory_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmZHHistoryData");

        }

        private void AddTabPage(string nameSpace, string typeName)
        {
            try
            {
                string assemblyPath = Path.Combine(Application.StartupPath, nameSpace + ".exe");
                string fullTypeName = nameSpace + "." + typeName;

                // 尝试从缓存获取 Assembly
                if (!_assemblyCache.TryGetValue(assemblyPath, out Assembly assembly))
                {
                    if (!File.Exists(assemblyPath))
                    {
                        MessageBox.Show($"无法找到程序集文件：{assemblyPath}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    assembly = Assembly.LoadFrom(assemblyPath);
                    _assemblyCache[assemblyPath] = assembly;
                }

                // 尝试从缓存获取 Type
                if (!_typeCache.TryGetValue(fullTypeName, out Type type))
                {
                    type = assembly.GetType(fullTypeName);
                    if (type == null)
                    {
                        MessageBox.Show($"在程序集 {nameSpace}.exe 中无法找到类型：{typeName}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    _typeCache[fullTypeName] = type;
                }

                // 检查是否已存在同名窗体的 TabPage
                foreach (XtraTabPage existingPage in xtraTabMain.TabPages)
                {
                    if (existingPage.Tag is Form existingForm && existingForm.GetType() == type)
                    {
                        xtraTabMain.SelectedTabPage = existingPage;
                        existingForm.Activate();
                        return;
                    }
                }

                // 创建新窗体实例并添加到 TabPage
                Form formInstance = (Form)Activator.CreateInstance(type);
                formInstance.Name = typeName; // 使用 TypeName 作为 Name
                formInstance.Tag = formInstance; // 将窗体实例自身作为 Tag
                formInstance.ControlBox = false;
                formInstance.TopLevel = false;
                formInstance.Visible = true;
                formInstance.Dock = DockStyle.Fill;

                XtraTabPage newTabPage = new XtraTabPage
                {
                    Tag = formInstance,
                    Text = formInstance.Text,
                    AutoScroll = true,
                    //修改选项卡的字体大小
                    //Font = new Font("Tahoma", 12, FontStyle.Regular),
                    //ImageOptions = { Image = formInstance.Icon.ToBitmap() } // 使用窗体的图标
                };
                newTabPage.Controls.Add(formInstance);

                xtraTabMain.TabPages.Add(newTabPage);
                xtraTabMain.SelectedTabPage = newTabPage;

                if (!xtraTabMain.Visible)
                {
                    xtraTabMain.Visible = true;
                    xtraTabMain.BringToFront();
                }
            }
            catch (FileNotFoundException fnfEx)
            {
                MessageBox.Show($"加载窗体失败：找不到依赖文件。\n{fnfEx.Message}", "文件未找到", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (TypeLoadException tlEx)
            {
                MessageBox.Show($"加载窗体失败：无法加载类型 '{typeName}'。\n{tlEx.Message}", "类型加载错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                // 捕获其他通用异常
                MessageBox.Show($"打开功能时发生未知错误：\n{ex.Message},Trace信息是\n{ex.StackTrace}", "异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            barStatusDate.Caption = DateTime.Now.ToString("F");
        }

        private void xtraTabMain_CloseButtonClick(object sender, EventArgs e)
        {
            DevExpress.XtraTab.ViewInfo.ClosePageButtonEventArgs EArg = (DevExpress.XtraTab.ViewInfo.ClosePageButtonEventArgs)e;
            string name = EArg.Page.Text;//得到关闭的选项卡的text
            foreach (XtraTabPage page in xtraTabMain.TabPages)//遍历得到和关闭的选项卡一样的Text
            {
                if (page != null)
                {
                    //先释放页面
                    if (page.Tag != null)
                    {
                        var form = page.Tag as Form;

                        if (form != null && form.Text == name)
                        {
                            form.Close();
                            xtraTabMain.TabPages.Remove(page);
                            page.Dispose();
                            return;
                        }
                    }


                }

            }
        }

        private void CloseAllTag()
        {
            for (int i = 0; i < xtraTabMain.TabPages.Count; i++)//遍历得到和关闭的选项卡一样的Text
            {
                if (xtraTabMain.TabPages[i] != null)
                {
                    //先释放页面
                    if (xtraTabMain.TabPages[i].Tag != null)
                    {
                        var form = xtraTabMain.TabPages[i].Tag as Form;

                        if (form != null)
                        {
                            form.Close();
                            xtraTabMain.TabPages.Remove(xtraTabMain.TabPages[i]);


                        }
                    }


                }
            }
        }

        public void CloseTabPage(Form childForm)
        {
            // 寻找对应的 TabPage，并关闭它  
            foreach (XtraTabPage tabPage in xtraTabMain.TabPages)
            {
                var control = tabPage.Controls[0]; // 假设每个TabPage只有一个嵌入的窗体  
                if (control == childForm)
                {
                    xtraTabMain.TabPages.Remove(tabPage);
                    break;
                }
            }
        }

        private void FrmMain3D_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (XtraMessageBox.Show("即将关闭所有窗体,并且退出程序", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                CloseAllTag();

            }
            else
            {
                e.Cancel = true;
            }
        }

        private void xtraTabMain_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 直接打开sqliteStudio
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSqlite_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //string exePath = Application.StartupPath + "\\Sqlitestudio\\SQLiteStudio.exe"; // 请根据实际路径修改  

            //// 使用 Process.Start 打开 EXE 文件  
            //Process.Start(exePath);
            this.AddTabPage("twistmachinev2", "FrmSqliteQuery");

        }



        private void btnDictionary_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmZHDictionary");
        }

        private void btnPrintTemplate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmZHPrintTemplate");
        }

        private void btnTestProject_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmTestProject");
        }

        private void btnInterface_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmInterface");
        }

        private void btnLog_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmLogViewer");
        }




        private void btnTorqueTest_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //this.AddTabPage("twistmachinev2", "FrmTorqueTest");

            this.AddTabPage("twistmachinev2", "FrmZHLineTorqueTest");


        }

        private void btnTorqueSettings_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmTorqueSettings");
        }

        /// <summary>
        /// 基础信息设定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInformation_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmInformation");
        }

        private void btnTestTorqueDevice_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmDeviceTest");
        }

        private void btnChangeLog_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmChangeLog");
        }

        private void btnOPCUATest_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void btnOPCUATest_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmOPCUATest");
        }

        private void btnOPCUABrowser_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmOPCUAServerBrowser");
        }

        private void btnOPCUAManagementMonitor_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmOpcUaDataMonitor");


        }

        private void btnBIngdingOPCUATest_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void btnIO_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmIO");
        }

        private void btnAlarmInfo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmAlarmInfo");
        }

        private void btnRun_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmRunForm");
        }

        private void btnRecipe_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.AddTabPage("twistmachinev2", "FrmRecipe");
        }
    }

}
